package org.jacp.demo.repository;

import java.io.File;
import java.io.IOException;
import java.util.Properties;

import jdbm.RecordManager;
import jdbm.RecordManagerFactory;
import jdbm.RecordManagerOptions;
import jdbm.btree.BTree;
import jdbm.helper.StringComparator;

/**
 * Loads Image description like name, size, position in cache image an so on
 * from storage
 * 
 * @author Andy Moncsek
 * 
 */

public class ImageInfoCacheRepository {

    private RecordManager recman;
    private BTree tree;

    public ImageInfoCacheRepository() {
	final Properties props = new Properties();
	props.put(RecordManagerOptions.CACHE_SIZE, "10000");
	try {
	    recman = RecordManagerFactory.createRecordManager("imageCache",
		    props);

	    // create or load image cache
	    final long recid = recman.getNamedObject("images");
	    if (recid != 0) {
		System.out.println("Reloading existing image cache...");
		tree = BTree.load(recman, recid);

	    } else {
		System.out.println("Creating new image cache...");
		tree = BTree.createInstance(recman, new StringComparator());
		recman.setNamedObject("images", tree.getRecid());
	    }
	} catch (final IOException e) {
	    e.printStackTrace();
	}
    }

    public synchronized void insertCacheRecord(final String file,
	    final String contentMeta) {
	try {
	    tree.insert(file, contentMeta, false);
	    recman.commit();
	} catch (final IOException e) {
	    // TODO Auto-generated catch block
	    e.printStackTrace();
	}

    }

    public synchronized String[] getCacheRecord(final String file) {
	Object result = null;
	try {
	    result = tree.find(file);
	} catch (final IOException e) {
	    e.printStackTrace();
	}
	if (result != null && result instanceof String) {
	    final String entry = (String) result;
	    return entry.split(":");
	}

	return new String[0];
    }

    public final synchronized String[] getEntriesForFileName(
	    final String fileName) {

	return null;
    }

    public final synchronized String[] getEntriesForFileNameFromFile(
	    final String fileName, final File cacheEntry) {

	return null;
    }

    public final synchronized String[] getEntriesForFileNameFromRecord(
	    final String fileName, final String[] cacheEntry) {

	return null;
    }

    public final synchronized void storeImageEntry() {

    }

}
